const fs = require('fs');
const path = require('path');
const express = require('express');

const app = express();

// function resolve(dir) {
//   return path.join(__dirname, dir);
// }
// 引入静态文件 否则运行报错
app.use(express.static(path.resolve(__dirname, '../Server/app/public/client')));

const { createBundleRenderer } = require('vue-server-renderer');
const bundle = require('../Server/app/public/server/vue-ssr-server-bundle.json');
const clientManifest = require('../Server/app/public/client/vue-ssr-client-manifest.json');

const renderer = createBundleRenderer(bundle, {
  runInNewContext: false,
  template: fs.readFileSync('./public/index.temp.html', 'utf-8'),
  clientManifest
});

function renderToString(context) {
  return new Promise((resolve, reject) => {
    renderer.renderToString(context, (err, html) => {
      err ? reject(err) : resolve(html);
    });
  });
}

app.get('/login', async (req, res) => {
  console.log('req:', req.url);
  const context = {
    title: 'ssr test',
    url: req.url
  };
  try {
    req.res.setHeader('Content-Type', 'text/html');
    const html = await renderToString(context);
    // console.log('html:', html);
    res.end(html);
  } catch (err) {
    console.log(err);
  }
});

app.listen(3000, () => {
  console.log(`server started at localhost:3000`);
});